<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 17-11-3
 * Time: 下午2:15
 */

namespace App\Http\Controllers\Admin\Portal;


use App\Http\Controllers\Admin\AdminController;
use App\Repositories;
use Illuminate\Http\Request;

abstract class DocumentController extends AdminController
{
    /**
     * 当前文档模型名
     * @var string
     */
    protected $documentType = 'news';

    /**
     * 初始化操作
     * UserController constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->setTemplatePrefix(config('admin.systems.template_prefix', 'admin.').'portal.document.');
    }

    /**
     * 获取当前控制器服务仓库对象
     * @return mixed
     */
    public function getServiceRepository() : Repositories\Portal\DocumentRepository
    {
        return Repositories\Portal\DocumentRepository::getInstance();
    }

    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $documentType = $this->documentType;

        $categoryId = $request->input('search.category_id', 0);
        $keywords = $request->input('search.keywords', null);

        $data = $this->getServiceRepository()->getAdminPaginateData($documentType, $categoryId, $keywords);

        return $this->fetch('index', [
            'data'=>$data,
            'documentType' => $this->documentType,
            'sourceList' => config('admin.systems.document_source_list'),
            'categoryList' => Repositories\Portal\CategoryRepository::getInstance()->getCategoryList(null, null, $documentType)->toArray(),
            'categoryNotAllowIdList' => Repositories\Portal\CategoryRepository::getInstance()->getNotAllowContentIdList()->toArray(),
            'search' => ['categoryId'=>$categoryId, 'keywords'=>$keywords]
        ]);
    }

    /**
     * 更新操作
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function edit(Request $request)
    {
        if (strtolower($request->method()) !== 'post') {
            return $this->editPage($request);
        }

        $document = $request->input('document', []);
        $cover = $document['cover'];
        $document['cover'] = $cover['url'];
        $document['cover_id'] = $cover['id'];
        $extend = $request->input('extend', []);

        $model = $this->getServiceRepository()->saveData($document, $extend, $this->documentType, $request->input('action', 'add'));

        $position = $request->input('position', []);
        if ($position) {
            foreach ($position as $key=>$value) {
                $pos = Repositories\Basic\AdvRepository::getInstance()->getAdvDataListByName($value);
                $positionDetail = Repositories\Basic\AdvRepository::getInstance()->getAdvListByObject($model->id, $model->document_type, $pos->id);
                $action = $positionDetail ? 'edit' : 'add';
                $positionInfo = [
                    'id' => get_value($positionDetail, 'id', 0),
                    'adv_id' => $pos->id,
                    'title' => $model->title,
                    'big_title' => $model->title,
                    'description' => $model->description,
                    'cover' => $model->cover,
                    'content' => $model->cover,
                    'links' => '/'.$model->document_type.'/detail/'.$model->id,
                    'object_id' => $model->id,
                    'object_model' => $model->document_type,
                    'created_at' => $model->fixed_release_time,
                ];

                Repositories\Basic\AdvRepository::getInstance()->saveData($positionInfo, $action);
            }

        }

        return $this->success('更新'.get_value(config('admin.systems.document_type_list', []), $this->documentType, '文档').'成功');
    }

    /**
     * 默认获取详情方法
     * @param Request $request
     * @return array
     */
    protected function getDetail(Request $request)
    {
        $id = $request->route('id');

        $categoryId = $request->input('category_id', 0);

        $detail = $this->getServiceRepository()->getDetailById($id);

        return [$id, $categoryId, $detail];
    }

    /**
     * 编辑页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    protected function editPage(Request $request)
    {
        $documentType = $this->documentType;

        list($id, $categoryId, $detail) = $this->getDetail($request);

        if (empty($detail)) {
            return $this->error('该文档不存在');
        }

        if (empty($id)) {
            $action = 'add';
            $detailExtend = [];
        } else {
            $detailExtend = $detail->$documentType;
            $action = 'edit';
        }

        //  推荐位
        $positionList = get_value(config('admin.systems.model_position_list'), $documentType , []);
        $posList = $posInputValue = [];
        if (!empty($positionList)) {
            foreach ($positionList as $key=>&$value) {
                $position = Repositories\Basic\AdvRepository::getInstance()->getAdvDataListByName($value);
                $posIdList = [];
                if ($position) {
                    foreach ($position->data as $k=>$v) {
                        $posIdList[$k] = $v->object_id;
                    }
                    if (in_array($id, $posIdList)) {
                        $posInputValue[$key] = $position->name;
                    }
                    $posList[$position->name] = $position->title;
                }

            }
        }

        return $this->fetch('edit', [
            'metaTitle' => '更新'.get_value(config('admin.systems.document_type_list', []), $documentType, '文档').'信息',
            'postUrl'   => get_admin_url('portal/'.$documentType.'/edit', ['id'=>$id]),
            'action' => $action,
            'categoryId' => $categoryId,
            'documentType' => $documentType,
            'documentTypeTitle' => get_value(config('admin.systems.document_type_list', []), $documentType, '文档'),
            'detail' => $detail,
            'detailExtend' => $detailExtend,    //  扩展表信息
            'categoryList' => Repositories\Portal\CategoryRepository::getInstance()->getCategoryList(null, null, $documentType)->toArray(),
            'categoryNotAllowIdList' => Repositories\Portal\CategoryRepository::getInstance()->getNotAllowContentIdList()->toArray(),
            'sourceList' => config('admin.systems.document_source_list'),
            'defaultCover' => $documentType == 'news' ? '' : '',
            'posList' => $posList,
            'posInputValue' => $posInputValue,
        ]);
    }

    /**
     * 更新文档状态
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function setStatus(Request $request)
    {
        if (strtolower($request->method()) == 'get') {
            $ids = $request->route('ids', '');
        } else {
            $ids = $request->input('ids', []);
        }

        $status = $request->route('status');

        $this->getServiceRepository()->setStatus($ids, $status);

        return $this->success('更新文档状态成功');
    }
}